package com.example.user1.util;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.time.format.DateTimeFormatter;
import java.util.Random;

/**
 * 流程ID生成器
 *
 * @author yu.wang
 * @date 2022/08/18  19:06
 **/
@Slf4j
@Component
public class IdUtils {

    private static RedissonClient client;

    private static final String NUM_LIST = "1234567890";

    private static Random random = new Random();

    public IdUtils(RedissonClient client) {
        IdUtils.client = client;
    }



    /**
     * 服务前缀
     */
    public static final String SERVER_PREFIX = "DEM_";

    public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    public static Long nextId(){
       return nextId("");
    }

    public static Long nextId(String prefix) {
        prefix = prefix != null ? prefix : "FL";
        String key = SERVER_PREFIX.concat(prefix);
        // 通过redis的自增获取序号
        RAtomicLong atomicLong = client.getAtomicLong(key);
        long num = atomicLong.incrementAndGet();
        // num不够5位数时左补齐0
        return num;
    }

    /**
     * 生成随机数字
     * @param num
     * @return
     */
    public static String randomNum(int num) {
        if(num<=0){
            return "0";
        }
        random.setSeed(System.currentTimeMillis());
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < num; j++) {
            sb.append(NUM_LIST.charAt(random.nextInt(10)));
        }
        return sb.toString();
    }
}
